package com.example.commentserver.manager;

import com.example.commentserver.vo.CommentVO;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息缓存
 *
 */
@Service
public class CommentCacheManager {
    @Autowired
    private RedissonClient redissonClient;
    private static final String COMMENT_CHACHE = "COMMENT_CHACHE:%s";
    /**
     * 详情页评论超时时间
     */
    @Value("${commentVO.cache.expire.minutes:1440}")
    private int expireMinutes;
    private static final Logger LOGGER = LoggerFactory.getLogger(CommentCacheManager.class);
    /**
     * 获取缓存中的评论VO
     *
     * @param id
     * @return
     */
    public List<CommentVO> getCommentCache(String id) {
        try {
            RBucket<List<CommentVO>> keyObject =
                    redissonClient.getBucket(String.format(COMMENT_CHACHE, id));
            return keyObject.get();
        } catch (Exception e) {
            LOGGER.error("CommentCacheManager.getCommentCache 从缓存中获取数据异常，id:【{}】异常信息：", id, e);
            return null;
        }
    }

    public void saveCommentVOCache(String id, List<CommentVO> commentVODB) {
        if (id == null || commentVODB == null) {
            return;
        }
        RBucket<List<CommentVO>> keyObject =
                redissonClient.getBucket(String.format(COMMENT_CHACHE, id));
        keyObject.set(commentVODB,
                expireMinutes,
                TimeUnit.MINUTES);
    }
}
